package com.letao.server.utils;

import com.alibaba.fastjson.JSON;
import com.letao.server.dto.EsShopInfoDTO;
import com.letao.server.dto.EsSpuInfoDTO;
import com.letao.server.entity.ShopInfo;
import com.letao.server.entity.SpuInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

@Slf4j
public class EsUtils {
    private RestHighLevelClient restHighLevelClient;

    public EsUtils() {
        this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.126.130:9200")
        ));
    }

    public void insertAndUpdateShop(ShopInfo t) {
        try {
            EsShopInfoDTO e = new EsShopInfoDTO(t);
            IndexRequest request = new IndexRequest("shop").id(t.getId().toString());
            String jsonString = JSON.toJSONString(e);
            request.source(jsonString, XContentType.JSON);
            IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteShop(ShopInfo t) {

        DeleteRequest request = new DeleteRequest("shop", t.getId().toString());
        try {
            DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public void insertAndUpdateSpu(SpuInfo data) {
        try {
            EsSpuInfoDTO e = new EsSpuInfoDTO(data);
            IndexRequest request = new IndexRequest("spu").id(data.getId().toString());
            String jsonString = JSON.toJSONString(e);
            request.source(jsonString, XContentType.JSON);
            IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteSpu(SpuInfo data) {
        DeleteRequest request = new DeleteRequest("spu", data.getId().toString());
        try {
            DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
